// dao/matchMessageDao.js
// 实现与MySQL交互
var mysql = require('mysql');
var $conf = require('../conf/db');
var $util = null; //require('../util/util');
var $sql = require('./matchMessageSqlMapping');
var logger = require('../util/log').logger;

// 使用连接池，提升性能
var pool = mysql.createPool($conf.mysql);

// 向前台返回JSON方法的简单封装
var jsonWrite = function (res, ret) {
    if (typeof ret === 'undefined') {
        res.json({
            code : '1',
            msg : '操作失败'
        });
    } else {
        res.json(ret);
    }
};

module.exports = {
    update : function (param, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error("DB Connection Error: " + err.message);
                return;
            }
            var useDbSql = "USE ummor";
            connection.query(useDbSql, function (err) {
                if (err) {
                    console.log("USE Error: " + err.message);
                    return;
                }
                logger.info('USE succeed');
            });

            // 建立连接，更新赛事信息状态
            connection.query($sql.update, [param.game_status, param.match_msg_id], function (err, result) {
                //console.log("query:"+err+":"+result[0].account);
                if (result) {
                    logger.info('更新赛事信息状态成功,sql:' + $sql.update + ',match_msg_id:' + param.match_msg_id + ',game_status' + param.game_status);
					
                    connection.query($sql.updateMatch, [param.game_status, param.match_msg_id], function (err2, result2) {
						logger.info('matchMessageDao-updateMatch:sql:'+$sql.updateMatch+',match_msg_id:' + param.match_msg_id + ',game_status' + param.game_status);
                        if (err2) {
                            logger.error('matchMessageDao-updateMatch failed:'+err2.message);
                        }else{
							logger.info('matchMessageDao-updateMatch success!');
						}
                        if (callback) {
                            callback(err, result);
                        }
                        connection.release();
                    });
                }
                if (err) {
                    console.log('matchMessageDao-update error:'+err.message);
                    //jsonWrite(res, result);
                    if (callback) {
                        callback(err, result);
                        // 释放连接
                        connection.release();
                        return;
                    }
                }

            });
        });
    },
    /*
     * 更新用户比分
     */
    update_user_score : function (param, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error("matchMessageDao:DB Connection Error: " + err.message);
                return;
            }
            var useDbSql = "USE ummor";
            connection.query(useDbSql, function (err) {
                if (err) {
                    console.log("matchMessageDao:USE Error: " + err.message);
                    return;
                }
            });

            // 建立连接，更新比分状态
            logger.info('update_user_score:' + $sql.update_user_score + ';match_msg_id=' + param.match_msg_id + ',user_id=' + param.user_id);
            connection.query($sql.update_user_score, [param.match_msg_id, param.user_id], function (err, result) {
                //console.log("query:"+err+":"+result[0].account);
                if (result) {
					connection.release();
				}
                if (err) {
                    console.log(err.message);
                    //jsonWrite(res, result);
                    if (callback) {
                        callback(err, result);
                        // 释放连接
                        connection.release();
                        return;
                    }
                }

            });
        });
    },
    /*
     * 更新比赛信息比分
     */
    update_match_msg_score : function (param, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error("DB Connection Error: " + err.message);
                return;
            }
            var useDbSql = "USE ummor";
            connection.query(useDbSql, function (err) {
                if (err) {
                    console.log("USE Error: " + err.message);
                    return;
                }
                logger.info('USE succeed');
            });

            // 建立连接，更新比分状态
            logger.info('update_match_msg_score:' + $sql.update_match_msg_score + ';homescore=' + param.homescore + ',guestscore=' + param.guestscore + ',match_msg_id=' + param.match_msg_id);
            connection.query($sql.update_match_msg_score, [param.homescore, param.guestscore, param.match_msg_id], function (err, result) {
                //console.log("query:"+err+":"+result[0].account);
                if (result) {
					connection.release();}
                if (err) {
                    console.log(err.message);
                    //jsonWrite(res, result);
                    if (callback) {
                        callback(err, result);
                        // 释放连接
                        connection.release();
                        return;
                    }
                }

            });
        });
    },

    /*
     * 更新比赛信息状态
     */
    update_match_msg_status : function (param, callback) {
		logger.debug('matchMessageDao.update_match_msg_status try to getConnection...');
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error("DB Connection Error: " + err.message);
                return;
            }
            var useDbSql = "USE ummor";
            connection.query(useDbSql, function (err) {
                if (err) {
                    console.log("USE Error: " + err.message);
                    return;
                }
                logger.info('USE succeed');
            });

            // 建立连接，更新比赛状态
            logger.info('matchMessageDao-select_match_msg_status:sql:'+$sql.select_match_msg_status);
            connection.query($sql.select_match_msg_status, [param.match_msg_id], function (err, rows, fields) {
                //console.log("query:"+err+":"+result[0].account);
                if (!err) {
                    if (rows.length === 0) { //新增一条状态
					logger.info('matchMessageDao-starting to insert_match_msg_status...');
                        connection.query($sql.insert_match_msg_status, [param.match_msg_id, param.sport_id, param.home_team_score, param.guest_team_score, param.game_time, param.all_seconds, param.last_stage, param.last_score_text], function (err, result) {
                            if (err) {
                                logger.error('matchMessageDao-insert_match_msg_status execute sql failed'+err.message);
                            } else {
                                logger.info('matchMessageDao-insert_match_msg_status execute sql success');
                            }
							connection.release();
							logger.debug('insert_match_msg_status coonection release!');
                        });
                    } else { //更新当前状态
					logger.info('matchMessageDao-starting to update_match_msg_status...');
                        connection.query($sql.update_match_msg_status, [param.sport_id, param.home_team_score, param.guest_team_score, param.game_time, param.all_seconds, param.last_stage, param.last_score_text, param.match_msg_id], function (err, result) {
                            if (err) {
                                logger.error('matchMessageDao-update_match_msg_status execute sql failed'+err.message);
                            } else {
                                logger.info('matchMessageDao-update_match_msg_status execute sql success');
                            }
							connection.release();
							logger.debug('update_match_msg_status coonection release!');
                        });
                    }
                }
                if (err) {
                    console.error('matchMessageDao-select_match_msg_status faild:'+err.message);
                    //jsonWrite(res, result);
                    if (callback) {
                        callback(err, result);
                        // 释放连接
                        connection.release();
                        return;
                    }
                }

            });
        });
    },
    /*
     * 查询比赛信息状态
     */
    select_match_msg_status : function (param, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error("DB Connection Error: " + err.message);
                return;
            }
            var useDbSql = "USE ummor";
            connection.query(useDbSql, function (err) {
                if (err) {
                    console.log("USE Error: " + err.message);
                    return;
                }
                logger.info('USE succeed');
            });

            // 建立连接，更新比赛状态
            logger.info('select_match_msg_status:');
            connection.query($sql.select_match_msg_status, [param.match_msg_id], function (err, rows, fields) {
                //console.log("query:"+err+":"+result[0].account);
                if (!err) {
                    if (rows.length === 0) {
                        if (callback) {
                            callback(err, {
                                rows : {}
                            });
                        }
                    } else {
                        if (callback) {
                            callback(err, {
                                rows : rows[0]
                            });
                        }
                    }
					connection.release();
					logger.debug('select_match_msg_status connection release');
                }
                if (err) {
                    console.log(err.message);
                    //jsonWrite(res, result);
                    if (callback) {
                        callback(err, result);
                        // 释放连接
                        connection.release();
						logger.debug('select_match_msg_status connection release');
                        return;
                    }
                }

            });
        });
    },
    /*
     * 更新比赛结果
     */
    updateMatchResult : function (param, callback) {
		logger.debug('invoke matchMessageDao.updateMatchResult..');
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error("DB Connection Error: " + err.message);
                return;
            }else{
				logger.debug('matchMessageDao-updateMatchResult:getConnection is ok!');
			}
            var useDbSql = "USE ummor";
            connection.query(useDbSql, function (err) {
                if (err) {
                    console.log("USE Error: " + err.message);
                    return;
                }
            });

            // 建立连接，更新比赛状态
            logger.info('updateMatchResult:select match result from match_message..');
            connection.query($sql.select_match_msg, [param.match_msg_id], function (err, rows, fields) {
                //console.log("query:"+err+":"+result[0].account);
                if (!err) {
                    if (rows.length === 0) {
                        if (callback) {
                            callback(err, {
                                rows : {}
                            });
                        }
						connection.release();
                    } else {

                        try {
                            var msgInfo = rows[0];
                            //host_team_id,away_team_id,host_team_score,away_team_score
                            var host_team_id = msgInfo.host_team_id;
                            var away_team_id = msgInfo.away_team_id;
                            var host_team_score = msgInfo.host_team_score;
                            var away_team_score = msgInfo.away_team_score;
                            logger.debug('host_team_id:,' + host_team_id + 'away_team_id:' + away_team_id + ',host_team_score:' + host_team_score + ',away_team_score:' + away_team_score);

                            //判断谁赢了
                            var host_win = (host_team_score > away_team_score);
                            var away_win = (away_team_score > host_team_score);
                            var pingju = (host_team_score === away_team_score);
                            var host_count = 0;
                            if (host_win) {
                                logger.debug('host is win');

                                //update ummor_match_team_signin set score=score+?,victory=vicory+?,fail=fail+?,abandon=abandon+? where team_id=? and union_id in (select union_id from ummor_match_message where match_msg_id=?)
                                connection.query($sql.update_match_team_signin, [1, 1, 0, 0, host_team_id, param.match_msg_id], function (err, result) {
                                    host_count++;
                                    if (err) {
                                        logger.error('set host info failed' + err.message);
                                    } else {
                                        logger.debug('set host info success!');
                                    }
                                    if (host_count === 2) {
                                        connection.release();
                                    }
                                });

                                connection.query($sql.update_match_team_signin, [0, 0, 1, 0, away_team_id, param.match_msg_id], function (err, result) {
                                    host_count++;
                                    if (err) {
                                        logger.error('set away info failed' + err.message);
                                    } else {
                                        logger.debug('set away info success!');
                                    }
                                    if (host_count === 2) {
                                        connection.release();
                                    }
                                });
                            } else if (away_win) {
                                logger.debug('away is win');
                                //update ummor_match_team_signin set score=score+?,victory=vicory+?,fail=fail+?,abandon=abandon+? where team_id=? and union_id in (select union_id from ummor_match_message where match_msg_id=?)
                                connection.query($sql.update_match_team_signin, [1, 1, 0, 0, away_team_id, param.match_msg_id], function (err, result) {
                                    host_count++;
                                    if (err) {
                                        logger.error('set away info failed' + err.message);
                                    } else {
                                        logger.debug('set away info success!');
                                    }
                                    if (host_count === 2) {
                                        connection.release();
                                    }
                                });

                                connection.query($sql.update_match_team_signin, [0, 0, 1, 0, host_team_id, param.match_msg_id], function (err, result) {
                                    host_count++;
                                    if (err) {
                                        logger.error('set host info failed' + err.message);
                                    } else {
                                        logger.debug('set host info success!');
                                    }
                                    if (host_count === 2) {
                                        connection.release();
                                    }
                                });
                            } else { //平局
                                logger.debug('pingju');
                                //update ummor_match_team_signin set score=score+?,victory=vicory+?,fail=fail+?,abandon=abandon+? where team_id=? and union_id in (select union_id from ummor_match_message where match_msg_id=?)
                                connection.query($sql.update_match_team_signin, [0, 0, 0, 1, away_team_id, param.match_msg_id], function (err, result) {
                                    host_count++;
                                    if (err) {
                                        logger.error('set away info failed' + err.message);
                                    } else {
                                        logger.debug('set away info success!');
                                    }
                                    if (host_count === 2) {
                                        connection.release();
                                    }
                                });

                                connection.query($sql.update_match_team_signin, [0, 0, 0, 1, host_team_id, param.match_msg_id], function (err, result) {
                                    host_count++;
                                    if (err) {
                                        logger.error('set host info failed' + err.message);
                                    } else {
                                        logger.debug('set host info success!');
                                    }
                                    if (host_count === 2) {
                                        connection.release();
                                    }
                                });
                            }
                        } catch (eeee) {
                            logger.debug(eeee.message);
                        }
                    }
                }
                if (err) {
                    console.log(err.message);
                    //jsonWrite(res, result);
                    if (callback) {
                        callback(err, result);
                        // 释放连接
                        connection.release();
                        return;
                    }
                }

            });
        });
    }
};
